import java.util.PriorityQueue;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-05
 * Time: 19:26
 */
//描述一个任务
class MyTimerTask implements Comparable<MyTimerTask>{
    private final long time;
    private final Runnable runnable;

    public MyTimerTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = (System.currentTimeMillis() + delay);
    }
    //执行run中的代码块
    public void run(){
        runnable.run();
    }
    //比较
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
    //获取时间
    public long getTime() {
        return time;
    }
}

class MyTimer {
    //创建线程
    Thread thread;
    //存放任务
    private final PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    //创建锁对象
    private final Object locker = new Object();
    //实例化任务
    public void schedule(Runnable runnable,long delay){
        synchronized (locker) {
            //实例化任务
            MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
            //添加任务
              queue.offer(myTimerTask);
            locker.notify();
        }
    }
    //扫描任务队列,执行任务的线程
    public MyTimer(){
        thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                //锁是保护队列
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask myTimerTask = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= myTimerTask.getTime()) {
                            queue.poll();
                            //执行任务
                            myTimerTask.run();
                        } else {
                            locker.wait(myTimerTask.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(() -> System.out.println("400"),400);
        myTimer.schedule(() -> System.out.println("300"),300);
        myTimer.schedule(() -> System.out.println("200"),200);
        myTimer.schedule(() -> System.out.println("100"),100);

        Thread.sleep(500);
        System.out.println("Hello Main");
    }
}